﻿using System;
using System.Collections.Generic;
using System.Text;
using Pervasive.Data.SqlClient;
using System.Data;

namespace SweetSQL.Data.Providers
{
    internal sealed class PsqlConnectionProvider : ConnectionProviderBase
    {
        public PsqlConnectionProvider(ConnectionParameters parameters)
            : base(parameters)
        { }

        public override void Connect()
        {
            if (!Connected)
            {
                StringBuilder builder = new StringBuilder("ServerName=");
                builder.Append(Parameters.DataSource);
                if (!string.IsNullOrEmpty(Parameters.Database))
                {
                    builder.Append(";ServerDSN=");
                    builder.Append(Parameters.Database);
                }
                if (!string.IsNullOrEmpty(Parameters.Username))
                {
                    builder.Append(";User ID=");
                    builder.Append(Parameters.Username);
                }
                if (!string.IsNullOrEmpty(Parameters.Password))
                {
                    builder.Append(";Password=");
                    builder.Append(Parameters.Password);
                }
                Util.AppendCustomProperties(builder, Parameters.CustomProperties);

                Connection = new PsqlConnection(builder.ToString());
                Connection.Open();
                Connected = true;
            }
        }

        public override IDbCommand CreateCommand(string sql)
        {
            return new PsqlCommand(sql, Connection as PsqlConnection, Transaction as PsqlTransaction) { CommandTimeout = CommandTimeout };
        }

        public override IDataParameter CreateParameter(string name, Type type, int index)
        {
            return new PsqlParameter(name, null);
        }

        public override object ConvertToClr(Type type, object value)
        {
            if (type == typeof(Guid))
            {
                return new Guid(value.ToString());
            }
            return base.ConvertToClr(type, value);
        }

        public override object ConvertToDatabase(Type type, object value)
        {
            if (type == typeof(Guid))
            {
                return ((Guid)value).ToString("N");
            }
            return base.ConvertToDatabase(type, value);
        }

        public override void Dispose()
        {
            //Not sure why but disposing transaction errors after a Commit()
            Transaction = null;
            if (Connection != null)
            {
                Connection.Dispose();
                Connection = null;
            }
        }
    }
}
